<?php

namespace lvzmen\yii\cms\widgets\navs;

use Yii;
use yii\base\Widget;
use yii\bootstrap\NavBar;

/**
 * A menu imitate the sidebar of https://docs.docker.com/get-started/
 *
 * @note It's depend on bootstrap;
 *
 * @example :
 * ```php

 * ```
 * @author chenzhiwei <chenzhiweiwk@qq.com>
 * @date   2021/08/31
 */
class Anchor extends Widget
{

    public $class = "cms-anchor bs-docs-sidebar";
    public $style = "";

    public function init()
    {
        parent::init(); // TODO: Change the autogenerated stub

        $this->addCss();
        $this->addJs();
    }

    public function run()
    {
        return "<div class='{$this->class}' id='cms-anchor'><ul class='nav nav-sidebar'></ul></div>";
    }


    public function addCss(){
        $css = <<<CSS
.cms-anchor {
    position: fixed;
    right: 10px;
    top: 70px; 
    width: 250px;
    overflow: auto;
    padding-top: 0px;
    padding-bottom: 20px;
    max-height: calc(100vh - 8px);
}
.cms-anchor .nav > li > a {
    position: relative;
    display: block;
    padding: 5px 15px;
}
.cms-anchor .nav > li > a:hover {
    background-color: white;
}
:target::before {
    content: "";
    display: block;
    margin-top: -70px;
    height: 80px;
    width: 1px;
}
.cms-anchor-H1 {
    margin-left: 0px;
}
.cms-anchor-H2 {
    margin-left: 20px;
}
.cms-anchor-H3 {
    margin-left: 40px;
}
.cms-anchor-H4 {
    margin-left: 60px;
}
.cms-anchor-H5 {
    margin-left: 80px;
}
.cms-anchor-H6 {
    margin-left: 100px;
}
CSS;
        $this->view->registerCss($css);
    }

    public function addJs(){
        $js = <<<JS
function createCatalogue(){
    //给所有标题配好id，便于锚点定位
    var id = 1;
    $.each($('.cms-article').find('h1,h2,h3,h4,h5,h6'),function(k,v){
        v.id = 'catalogue' + id++;
    });
    console.info('1111');
    var catalogue = "";
    $.each($('.cms-article').find('h1,h2,h3,h4,h5,h6'),function(k,v){
        catalogue = catalogue + "<li><a href='#" + v.id + "' class='cms-anchor-" + v.tagName + "'>" + v.innerText + "</a></li>";
    });
    $(".cms-anchor ul").empty().append(catalogue);
}
JS;
        $this->view->registerJs($js, 3  );
    }

}
